//*************************************************************
//                          TEmbeddedWB  CVS: 1.18            *
//                                                            *
//                     Freeware Component                     *
//                       For Delphi                           *
//                            by                              *
//                     Per Lindso Larsen                      *
//      Developing Team:                                      *
//          Eran Bodankin (bsalsa) -(bsalsa@bsalsa.com)       *
//          Serge Voloshenyuk SergeV@bsalsa.com)              *
//                                                            *
//     Contributors:                                          *
//            Neil Moss (NeilM@BuchananInternational.com)     *
//            Thomas Stutz -(smot777@yahoo.com)               *
//            Mathias Walter (mich@matze.tv)                  *
//                                                            *
//       Documentation and updated versions:                  *
//                                                            *
//               http://www.bsalsa.com                        *
//*************************************************************
{LICENSE:
THIS SOFTWARE IS PROVIDED TO YOU "AS IS" WITHOUT WARRANTY OF ANY KIND,
EITHER EXPRESSED OR IMPLIED INCLUDING BUT NOT LIMITED TO THE APPLIED
WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
YOU ASSUME THE ENTIRE RISK AS TO THE ACCURACY AND THE USE OF THE SOFTWARE
AND ALL OTHER RISK ARISING OUT OF THE USE OR PERFORMANCE OF THIS SOFTWARE
AND DOCUMENTATION. [YOUR NAME] DOES NOT WARRANT THAT THE SOFTWARE IS ERROR-FREE
OR WILL OPERATE WITHOUT INTERRUPTION. THE SOFTWARE IS NOT DESIGNED, INTENDED
OR LICENSED FOR USE IN HAZARDOUS ENVIRONMENTS REQUIRING FAIL-SAFE CONTROLS,
INCLUDING WITHOUT LIMITATION, THE DESIGN, CONSTRUCTION, MAINTENANCE OR
OPERATION OF NUCLEAR FACILITIES, AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS,
AIR TRAFFIC CONTROL, AND LIFE SUPPORT OR WEAPONS SYSTEMS. VSOFT SPECIFICALLY
DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR SUCH PURPOSE.

You may use/ change/ modify the component under 4 conditions:
1. In your website, add a link to "http://www.bsalsa.com"
2. In your application, add credits to "Embedded Web Browser"
3. Mail me  (bsalsa@bsalsa.com) any code change in the unit  for the benefit
   of the other users.
4. Please, consider donation in our web site!
{*******************************************************************************}


unit EmbeddedWB;

//EwbTools----------------------------------------------------------------------
{To remove the EwbTools, just add a dot like "{.$DEFINE...USE_EwbTools" or something.
and re-compile the package.}
{$DEFINE USE_EwbTools}
{ $DEFINE USE_EwbDDE}
interface

{$I EWB.inc}

uses
   {$IFDEF DELPHI_6_UP}Variants, {$ENDIF}
   Windows, Messages, Classes, Mshtml_Ewb, EWBAcc, Graphics, Controls, Forms,
   ExtCtrls, ActiveX, ShlObj, SHDocVw_EWB, UrlMon, EwbCore;

type
   TEmbeddedWB = class;

   {VerifyVersion}
   fn_VerifyVersionInfo = function(var VersionInformation: OSVERSIONINFOEX;
      dwTypeMask: DWORD; dwlConditionMask: LONGLONG): BOOL; stdcall;
   fn_VerSetConditionMask = function(ConditionMask: LONGLONG; TypeMask: DWORD;
      Condition: Byte): LONGLONG; stdcall;
   {Private events}
   TShowDialogEvent = procedure(Sender: TObject; h: THandle) of object;
   TWindowStateChangedEvent = procedure(Sender: TObject; dwFlags, dwValidFlagsMask: integer) of object;

   TShortCuts = class(TPersistent)
   private
      fOwner: TEmbeddedWB;
      function getVal(const Index: Integer): Boolean;
      procedure setVal(const Index: Integer; const Value: Boolean);
    function getCtrlCharMask: string;
    function IsCtrlCharMask: Boolean;
    procedure setCtrlCharMask(const Value: string);
   public
      constructor Create(aOwner: TEmbeddedWB);
   published
      property CtrlCharMask: string read getCtrlCharMask write setCtrlCharMask stored
         IsCtrlCharMask;
      property DisableCTRL_A: Boolean index 1 read getVal write setVal stored False;
      property DisableCTRL_C: Boolean index 2 read getVal write setVal stored False;
      property DisableCTRL_F: Boolean index 3 read getVal write setVal stored False;
      property DisableCTRL_N: Boolean index 4 read getVal write setVal stored False;
      property DisableCTRL_P: Boolean index 5 read getVal write setVal stored False;
   end;

   TProxySettings = class(TPersistent)
   private
      FPort: Integer;
      FAddress: string;
      FUserName: string;
      FPassword: string;
      FAutoLoadProxy: Boolean;
   public
{$IFDEF USE_EwbTools}
      procedure SetProxy(UserAgent, Address: string); overload;
      procedure SetProxy(UserAgent, Address, UserName, Password: string; Port: integer); overload;
{$ENDIF}
   published
      property AutoLoadProxy: Boolean read FAutoLoadProxy write FAutoLoadProxy default False;
      property Port: Integer read FPort write FPort default 80;
      property Password: string read FPassword write FPassword;
      property Address: string read FAddress write FAddress;
      property UserName: string read FUserName write FUserName;
   end;

   TDialogBoxes = class(TPersistent)
   private
      FDisableAll: Boolean;
      FReplaceCaption: Boolean;
      FReplaceIcon: Boolean;
      FNewCaption: string;
   published
      property DisableAll: Boolean read FDisableAll write FDisableAll default False;
      property ReplaceCaption: Boolean read FReplaceCaption write FReplaceCaption default True;
      property ReplaceIcon: Boolean read FReplaceIcon write FReplaceIcon default True;
      property NewCaption: string read FNewCaption write FNewCaption;
   end;

   TDisableErrors = class(TPersistent)
   private
      FEnableDDE: Boolean;
      FfpExceptions: Boolean;
      FScriptErrorsSuppressed: Boolean;
      procedure SetfpExceptions(const Value: Boolean);
   published
      property EnableDDE: Boolean read FEnableDDE write FEnableDDE default True;
      property fpExceptions: Boolean read FfpExceptions write SetfpExceptions default True;
      property ScriptErrorsSuppressed: Boolean read FScriptErrorsSuppressed write FScriptErrorsSuppressed default True;
   end;

   TVisualEffects = class(TPersistent)
   private
      FDisableSounds: Boolean;
      FTextSize: Integer;
   published
      property TextSize: Integer read FTextSize write FTextSize default 2;
      property DisableSounds: Boolean read FDisableSounds write FDisableSounds default False;
   end;

   TMeasure = (mMetric, mUS);
   TPrintOrientationOption = (poPortrait, poLandscape);
   TMargins = class(TPersistent)
   private
      FLeft: Real;
      FRight: Real;
      FTop: Real;
      FBottom: Real;
   published
      property Left: Real read FLeft write FLeft;
      property Right: Real read FRight write FRight;
      property Top: Real read FTop write FTop;
      property Bottom: Real read FBottom write FBottom;
   end;

   TPrintOptions = class(TPersistent)
   private
      FEnabled: Boolean;
      FHTMLHeader: TStrings;
      FHeader: string;
      FFooter: string;
      FMargins: TMargins;
      FOrientation: TPrintOrientationOption;
      FMeasure: TMeasure;
      procedure SetHTMLHeader(const Value: Tstrings); 
   public
      HideSetup: Boolean;
      property Measure: TMeasure read FMeasure;
   published
      property Enabled: Boolean read FEnabled write FEnabled default False;
      property Margins: TMargins read FMargins write FMargins;
      property Header: string read FHeader write FHeader;
      property HTMLHeader: TStrings read FHTMLHeader write SetHTMLHeader;
      property Footer: string read FFooter write FFooter;
      property Orientation: TPrintOrientationOption read FOrientation write FOrientation;
   end;

   TVariantArray = array of OleVariant;
{$IFDEF USE_EwbTools}
   TSearchResult = (srNotFound, srEndOf, srFound);
   TSearchResults = set of TSearchResult;
   TSearchDirections = (sdDown, sdUp);
{$ENDIF}

   TEmbeddedWB = class(TCustomEmbeddedWB,
         IDocHostUIHandler,
         IInternetProtocol, //http://windowssdk.msdn.microsoft.com/en-us/library/ms528534.aspx
         IInternetProtocolRoot // http://msdn.microsoft.com/workshop/networking/pluggable/reference/ifaces/iinternetprotocolroot/iinternetprotocolroot.asp
         )

   private
      FEnableMessageHandler: Boolean;
      FProtSink: IInternetProtocolSink;
      FBindInfo: IInternetBindInfo;
      FAbout: string;
      FDisableErrors: TDisableErrors;
      FDialogBoxes: TDialogBoxes;
      FModified: Boolean;
      FOldWindowProc: TWndMethod;
      FOnShowDialog: TShowDialogEvent;
//      FOnWindowStateChanged: TWindowStateChangedEvent;
      FParentForm: TForm;
      FPrintOptions: TPrintOptions;
      FProxySettings: TProxySettings;
      FOnCloseQuery: TCloseQueryEvent;
      FShortCuts: TShortCuts;
      FSearchText: string;
      FTextRange: IHTMLTxtRange;
      FHTMLChar: Char;
      FUserAgent: string;
      FVisualEffects: TVisualEffects;
      m_bResizing: Boolean;
      m_bWinXPSP2: Boolean;
      RuntimeMeasure: TMeasure;
{$IFDEF USE_EwbTools}
      FLastDirection: TSearchDirections;
{$ENDIF}
      fDisabledPopupMenuItems: TIEPopupMenuItems;
      fHostNS, fHostCSS: string;
      function GetModified: Boolean;
      {$IFDEF USE_EwbDDE}
      procedure DDEWndProc(var AMsg: Messages.TMessage);
      {$ENDIF}
      procedure FormWndProc(var AMsg: Messages.TMessage);
      procedure GetPrintValues;
      procedure Hook;
      procedure SetAbout(Value: string);
      procedure SetModified(Value: Boolean);
      procedure UnHook;
{$IFDEF USE_EwbTools}
      function GetSelLength: Integer;
      function GetSelText: WideString;
      function GetSelTextHTML: WideString;
      procedure SetUserAgent;
{$ENDIF}
   protected
      FSearchTxtRange: IHTMLTxtRange;
      {IDocHostUIHandler Interface}
      function GetHostInfo(var pInfo: TDOCHOSTUIINFO): HRESULT; stdcall;
    {IInternetProtocolRoot Interface}
      function Abort(hrReason: HResult; dwOptions: DWORD): HResult; stdcall;
      function Continue(const ProtocolData: TProtocolData): HResult; stdcall;
      function Resume: HResult; stdcall;
      function Start(szUrl: PWideChar; OIProtSink: IInternetProtocolSink;
         OIBindInfo: IInternetBindInfo; grfPI, dwReserved: DWORD): HResult; stdcall;
      function Suspend: HResult; stdcall;
      function Terminate(dwOptions: DWORD): HResult; stdcall;
     {IInternetProtocol Interface}
      function Read(pv: Pointer; cb: ULONG; out cbRead: ULONG): HResult; stdcall;
      function Seek(dlibMove: LARGE_INTEGER; dwOrigin: DWORD; out libNewPosition: ULARGE_INTEGER): HResult; stdcall;
      function LockRequest(dwOptions: DWORD): HResult; stdcall;
      function UnlockRequest: HResult; stdcall;
      {$IFDEF USE_EwbDDE}
      function DDEExecute(iwParam: WPARAM; ilParam: LPARAM): LRESULT;
      function DDEInitiate(iwParam: WPARAM; ilParam: LPARAM): LRESULT;
      function DDETerminate(iwParam: WPARAM; ilParam: LPARAM): BOOL;
      {$ENDIF}
      function PrintMarginStr(M: Real): PChar;
   protected
      function FilterPopupMenu: Boolean; override;
      procedure DoFilterPopupMenu(ID: DWORD; Menu: HMENU; const Context: IDispatch); override;
   public
      SecurityManager: IInternetSecurityManager;
      ZoneManager: IInternetZoneManager;
{$IFDEF USE_EwbTools}
      function AddHtmlToAboutBlank(StringToHtml: string): Boolean;
      function CheckIfInRestricredList(Host: string; SecureSite: boolean): Boolean;
      function CheckIfInTrustedList(const Host: string; SecureSite: boolean): Boolean;
      function DocumentSource: string; // By Bitmaker
      function DocumentSourceText: string; // By Bitmaker
      function CheckOnlineStatus: Boolean;
      function DownloadFile(SourceFile, DestFile: string): Boolean;
      function EncodeUrl(const InputStr: string; const bQueryStr: Boolean): string;
      function DecodeUrl(const InputStr: string): string;
      function IsValidProtocol(const URL: string): Boolean;
      function FillForm(FieldName: string; Value: string): Boolean;
      function FrameCount: LongInt;
      function FrameCountFromDocument(SourceDoc: IHtmlDocument2): Integer;
      function GetBmpFromBrowser(FileName: string): Boolean;
      function GetCachedFileFromURL(strUL: string; var strLocalFile: string): Boolean;
      function GetCookie: string;
      function GetCookiesPath: string;
      function GetDefaultBrowserFromRegistry: string;
      function GetFavoritesPath: string;
      function GetFrameFromDocument(SourceDoc: IHtmlDocument2; FrameNo: Integer): IWebBrowser2;
      function GetHistoryPath: string;
      function GetIPAndHostName(var HostName, IPaddr, WSAErr: string): Boolean;
      function GetJpegFromBrowser(FileName: string; SourceHeight, SourceWidth,
         TargetHeight, TargetWidth: Integer): Boolean;
      function GetLastVisitedPage(var LastVisitedPage: string): Boolean;
      function GetSpecialFolderPath(CallerHandle: THandle; CSIDL: Integer): PChar;
      function GetSSLStatus(var SSLName, SSLDescription: string): Boolean;
      function GetURLSecurityZone(var ZoneName, ZoneDescription: string; var Icon: TIcon): Boolean;
      function GetWordAtCursor(const X, Y: Integer): string; // By M.Grusha
      function GetZoneAttributes(const URL: string): TZoneAttributes;
      function GetZoneIconToForm: Boolean;
      function IsGlobalOffline: Boolean;
      function NavigateToFrame(FrameList: string): IHtmlDocument2;
      function OpenAddressBook: Boolean;
      function OpenCalendar: Boolean;
      function OpenClient(Client: string): Boolean;
      function OpenEudoraMail: Boolean;
      function OpenGoogleMail: Boolean;
      function OpenHotmailMail: Boolean;
      function OpenNetMeeting: Boolean;
      function OpenNewsClient: Boolean;
      function OpenOutlookExpressMail: Boolean;
      function OpenOutlookMail: Boolean;
      function OpenRegistryEditor: Boolean;
      function OpenYahooMail: Boolean;
      function SaveDialogEx: string;
      function SaveLastVisitedPage: Boolean;
      function SearchString(const strText: string): Boolean;
      function SearchText(const Value: string; const iPos: Integer = 1): IHTMLTxtRange; //by JJM
      function SearchNextText(const Value: string; Direction: TSearchDirections = sdDown;
         AutoSelect: Boolean = True): TSearchResults; // by   Grusha M.A.
      function SetCharartersSet(const ACharactersSet: string): Boolean;
      function URLFromFavorites(const dotURL: string): string;
      function UrlFromHistory(ShellFolder: IShellFolder; pidl: PItemIDList): string;
      procedure AddToFavorites(URL, Title: string);
      procedure AddToRestrictedSiteList(URL: string);
      procedure AddToTrustedSiteList(URL: string);
      procedure AutoFillIEFormAndExcecute;
      procedure ClearCache;
      procedure ClearHistory;
      procedure ClearTypedUrls;
      procedure CreateDesktopShortcut;
      procedure CreateNewMail;
      procedure DisableNavSound(bDisable: Boolean);
      procedure ExploreFolder(Path: string);
      procedure GetThumbnail(var Image: TImage);
      procedure GetZoneIcon(IconPath: string; var Icon: TIcon);
      procedure GoAboutBlank;
      procedure GoDownloadFile(URL: string);
      procedure GoDownloadMaskedFile(SourceFile, TargetFile: string; Notify: Boolean);
      procedure GoNoHistory(const URL: string);
      procedure GoSearchInGoogle(SearchTerm: string);
      procedure GoSearchInMSN(SearchTerm: string);
      procedure GoSearchInYahoo(SearchTerm: string);
      procedure GoWithQueryDetails(Url, Query: string);
      procedure LoadFromImage(Image: TImage);
      procedure NavigateFolder(CSIDL: Integer);
      procedure OpenDialog;
      procedure OpenIEBrowserWithAddress;
      procedure OpenOtherWBFavorites;
      procedure PageSetup(UsePrintOptions: Boolean);
      procedure Print;
      procedure PrintPreview;
      procedure PrintPreviewExtended(nCMDShow: Integer);
      procedure PrintPreviewFromTemplate(const TemplateFileName: string);
      procedure PrintSetup;
      procedure PrintWithOptions;
      procedure RestoreApplicationFormSize;
      procedure SaveApplicationFormSize;
      procedure SaveDialog;
      procedure SaveImagesDialog;
      procedure SavePageTextDialog;
      procedure ScrollToBottom;
      procedure ScrollToPosition(X, Y: Integer);
      procedure ScrollToTop;
      procedure ScrollToID(ID: Integer);
      procedure ScrollToIDEx(ID: string); // by M.Grusha
      procedure SearchAndHighlight(const ACaption, APrompt: string; aText: string = '';
         ShowInputQuery: Boolean = False); // by M.Grusha
      procedure SendPageInMailAsAttachment(aOwner: TComponent; FileName, Subject, Body: string);
      procedure SendURLInMail;
      procedure SetNewHomePage(HomePage: string);
      procedure ShowFindDialog;
      procedure ShowIEVersionInfo;
      procedure ShowInternetOptions;
      procedure ShowOrganizeFavorites;
      procedure ShowPageProperties;
      procedure ViewPageFieldsToStrings(FieldList: TStrings);
      procedure ViewPageImagesToStrings(ImagesList: TStrings);
      procedure ViewPageLinksToStrings(LinksList: TStrings);
      procedure ViewPagePropertiesToStrings(PropertiesList: TStrings);
      procedure ViewPageSourceHtml;
      procedure ViewPageSourceHtmlToStrings(HtmlList: TStrings);
      procedure ViewPageSourceText;
      procedure ViewPageSourceTextToStrings(TextList: TStrings);
      procedure WorkOffline;
      procedure WorkOnline;
{$ENDIF}
      constructor Create(Owner: TComponent); override;
      destructor Destroy; override;
      function DesignMode: Boolean;
      function DocumentLoaded: Boolean;
      function GetDocument: IHtmlDocument2;
      function GetFrame(FrameNo: Integer): IWebbrowser2;
      function GetIEHomePage: string;
      class function GetIEHandle(WebBrowser: TEmbeddedWB; ClassName: string): HWND;
      function ImportCertFile(AFileName, AStoreType: string): Boolean;
      function LoadFrameFromStream(FrameNo: Integer; AStream: TStream): HRESULT;
      function LoadFrameFromStrings(Frameno: Integer; const AStrings: TStrings): HRESULT;
      function LoadFromStream(const AStream: TStream): HRESULT;
      function LoadFromStrings(const AStrings: TStrings): HRESULT; overload;
      function LoadFromStrings(const AStrings: TStrings; AddHtmlTags: Boolean): HRESULT; overload;
      function LoadFromString(const S: string): HRESULT; // By M.Grusha
      function LoadFromFile(const FileName: string): HRESULT; // By M.Grusha
      function SaveFrameToFile(FrameNo: Integer; const FName: string): HRESULT;
      function SaveFrameToStream(FrameNo: Integer; AStream: TStream): HRESULT;
      function SaveFrameToStrings(FrameNo: Integer; AStrings: TStrings): HRESULT;
      function SaveToFile(const FileName: string): HRESULT;
      function SaveToStream(AStream: TStream): HRESULT;
      function SaveToStrings(AStrings: TStrings): HRESULT;
      function VariantIsObject(const value: OleVariant): Boolean;

      procedure AssignEmptyDocument;
      procedure Copy;
      procedure Cut;
      procedure Go(Url: string);
      procedure InvokeCMD(InvokeIE: Boolean; Value1, Value2: Integer; var vaIn, vaOut: OleVariant);
      procedure InvokeIEServerCommand(Cmd: Integer);
      procedure Loaded; override;
      procedure LoadSettings;      
      procedure NavigatePidl(pidl: PItemIdlist);
      procedure Paste;
      procedure RefreshFrame(FrameNumber: Integer);
      procedure SelectAll;
      procedure ShowImportExportFavoritesAndCookies;
      procedure Wait;
      procedure Wait2;
      procedure WndProc(var Message: TMessage); override;

      property Modified: Boolean read GetModified write SetModified;
{$IFDEF USE_EwbTools}
      property SelLength: Integer read GetSelLength; // By M.Grusha
      property SelText: WideString read GetSelText; // By M.Grusha
      property SelTextHTML: WideString read GetSelTextHTML; // By M.Grusha
{$ENDIF}
   published
      property About: string read FAbout write SetAbout;
      property HostCSS: string read fHostCSS write fHostCSS;
      property HostNS: string read fHostNS write fHostNS;
      property EnableMessageHandler: Boolean read FEnableMessageHandler write FEnableMessageHandler default True;
      property DisabledPopupMenuItems: TIEPopupMenuItems read fDisabledPopupMenuItems
         write fDisabledPopupMenuItems default [];
      property DisableErrors: TDisableErrors read FDisableErrors write FDisableErrors;
      property DialogBoxes: TDialogBoxes read FDialogBoxes write FDialogBoxes;
      property OnCloseQuery: TCloseQueryEvent read FOnCloseQuery write FOnCloseQuery;
      property OnShowDialog: TShowDialogEvent read FOnShowDialog write FOnShowDialog;
      property PrintOptions: TPrintOptions read FPrintOptions write FPrintOptions;
      property ProxySettings: TProxySettings read FProxySettings write FProxySettings;
      property ShortCuts: TShortCuts read FShortCuts write FShortCuts;
      property UserAgent: string read FUserAgent write FUserAgent;
      property VisualEffects: TVisualEffects read FVisualEffects write FVisualEffects;
     {I am waiting for DISPID_WindowStateChanged from MS to finish it
     property OnWindowStateChanged: TWindowStateChangedEvent read FOnWindowStateChanged
         write FOnWindowStateChanged; }
   end;

implementation

uses
{$IFDEF USE_EwbTools}EWBTools, {$ENDIF}
{$IFDEF USE_EwbDDE}EwbDDE, {$ENDIF}
   Registry, SysUtils, Dialogs, Wcrypt2, ComObj, ShellAPI, OleServer, IEConst, WinInet;

var
   {$IFDEF USE_EwbDDE}
   HtmlFileApp, HtmlFileTopic: string; //All DDE variables
   fHtmlCommand, DontRespond: Boolean;
   FoldersApp, FoldersTopic: string;
   DDEHWND: THandle;
   {$ENDIF}
   InvokingPageSetup: Boolean;
   PrintingWithOptions: Boolean;
   //Boolean variablrs that must be global to restore settings for MDI cases:
   bPrintOptionsEnable: Boolean;
   wSaved8087CW: Word;
   bProxy: Boolean;
   bHook: Boolean;
   bNavSound: Boolean;
   bMessageH: Boolean;
   bOleInitialize: Boolean;
{ TShortCuts }

constructor TShortCuts.Create(aOwner: TEmbeddedWB);
begin
   inherited Create;
   fOwner := aOwner;
end;

function TShortCuts.getCtrlCharMask: string;
begin
  Result := fOwner.CtrlCharMask;
end;

function TShortCuts.getVal(const Index: Integer): Boolean;
begin
   Result := Pos(_MaskedChars[Index], fOwner.CtrlCharMask) > 0;
end;

function TShortCuts.IsCtrlCharMask: Boolean;
begin
  Result := CtrlCharMask <> 'N';
end;

procedure TShortCuts.setCtrlCharMask(const Value: string);
begin
  fOwner.CtrlCharMask := Value;
end;

procedure TShortCuts.setVal(const Index: Integer; const Value: Boolean);
begin
   if Value then
      begin
         if not getVal(Index) then
            fOwner.CtrlCharMask := fOwner.CtrlCharMask + _MaskedChars[Index];
      end
   else
      fOwner.CtrlCharMask := StringReplace(fOwner.CtrlCharMask, _MaskedChars[Index], '', []);
end;

//===Accesories=================================================================

procedure RemoveUserAgent;
const
   path = '\Software\Microsoft\Windows\CurrentVersion\Internet Settings\User Agent';
var
   Reg: TRegistry;
begin
   Reg := TRegistry.Create;
   with Reg do
      begin
         try
            RootKey := HKEY_CURRENT_USER;
            if OpenKey(Path, False) then
               begin
                  DeleteKey('Post Platform');
                  OpenKey(Path + '\Post Platform', True);
                  WriteString(USER_AGENT, '');
               end;
         finally
            CloseKey;
            Free;
         end;
      end;
end;

procedure RemoveProxy();
var
   list: INTERNET_PER_CONN_OPTION_LIST;
   dwBufSize: DWORD;
   hInternet: Pointer;
   Options: array[1..3] of INTERNET_PER_CONN_OPTION;
begin
   dwBufSize := sizeof(list);
   list.dwSize := sizeof(list);
   list.pszConnection := nil;
   list.dwOptionCount := High(Options);
   Options[1].dwOption := INTERNET_PER_CONN_FLAGS;
   Options[1].Value.dwValue := PROXY_TYPE_DIRECT or PROXY_TYPE_PROXY;
   Options[2].dwOption := INTERNET_PER_CONN_PROXY_SERVER;
   Options[2].Value.pszValue := PChar('');
   Options[3].dwOption := INTERNET_PER_CONN_PROXY_BYPASS;
   Options[3].Value.pszValue := '<local>';
   list.pOptions := @Options;
   hInternet := InternetOpen(PChar(''), INTERNET_OPEN_TYPE_DIRECT, nil, nil, 0);
   InternetSetOption(hInternet, INTERNET_OPTION_PER_CONNECTION_OPTION, @list, dwBufSize);
   InternetSetOption(hInternet, INTERNET_OPTION_REFRESH, nil, 0);
   InternetCloseHandle(hInternet);
end;

function IsWinXPSP2OrLater(): Boolean;
var
   osvi: TOSVersionInfoEx;
   dwlConditionMask: LONGLONG;
   op: Integer;
   hlib: THandle;
   VerifyVersionInfo: fn_VerifyVersionInfo;
   VerSetConditionMask: fn_VerSetConditionMask;
begin
   result := false;

   hLib := LoadLibrary('kernel32.dll');
   if (hLib <> 0) then
      begin
         @VerifyVersionInfo := GetProcAddress(hLib, 'VerifyVersionInfoA');
         @VerSetConditionMask := GetProcAddress(hLib, 'VerSetConditionMask');
         if ((@VerifyVersionInfo = nil) or (@VerSetConditionMask = nil)) then
            Exit;

         dwlConditionMask := 0;
         op := VER_GREATER_EQUAL;

    // Initialize the OSVERSIONINFOEX structure.
         ZeroMemory(@osvi, sizeof(OSVERSIONINFOEX));
         osvi.dwOSVersionInfoSize := sizeof(OSVERSIONINFOEX);
         osvi.dwMajorVersion := 5;
         osvi.dwMinorVersion := 1;
         osvi.wServicePackMajor := 2;
         osvi.wServicePackMinor := 0;

    // Initialize the condition mask.
         dwlConditionMask := VerSetConditionMask(dwlConditionMask, VER_MAJORVERSION, op);
         dwlConditionMask := VerSetConditionMask(dwlConditionMask, VER_MINORVERSION, op);
         dwlConditionMask := VerSetConditionMask(dwlConditionMask, VER_SERVICEPACKMAJOR, op);
         dwlConditionMask := VerSetConditionMask(dwlConditionMask, VER_SERVICEPACKMINOR, op);

    // Perform the test.
         result := VerifyVersionInfo(osvi, VER_MAJORVERSION or VER_MINORVERSION or
            VER_SERVICEPACKMAJOR or VER_SERVICEPACKMINOR, dwlConditionMask);
      end;
end;

function SaveDocToStrings(Doc: IDispatch; var AStrings: TStrings): HRESULT;
var
   IpStream: IPersistStreamInit;
   AStream: TMemoryStream;
begin
   AStream := TMemoryStream.Create;
   try
      IpStream := doc as IPersistStreamInit;
      if not Assigned(IpStream) then
         Result := S_False
      else
         if Succeeded(IpStream.save(TStreamAdapter.Create(AStream), True))
            then
            begin
               AStream.Seek(0, 0);
               AStrings.LoadFromStream(AStream);
               Result := S_OK;
            end
         else
            Result := S_False;
   except
      Result := S_False;
   end;
   AStream.Free;
end;

function SaveDocToStream(Doc: IDispatch; var AStream: TStream): HRESULT;
var
   IpStream: IPersistStreamInit;
begin
   if Doc <> nil then
      begin
         IpStream := Doc as IPersistStreamInit;
         Result := IpStream.save(TStreamAdapter.Create(AStream), True);
      end
   else
      Result := S_False;
end;

function SaveDocToFile(Doc: IDispatch; const FName: string): HRESULT;
var
   PFile: IPersistFile;
begin
   PFile := Doc as IPersistFile;
   Result := PFile.Save(StringToOleStr(FName), False);
end;

function GetRunTimeMeasure: TMeasure;
var
   Buf: array[1..10] of Char;
begin
   FillChar(Buf, SizeOf(Buf), 0);
   GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_IMEASURE, @Buf[1], SizeOf(Buf));
   if Buf[1] = '1' then
      Result := mUS
   else
      Result := mMetric;
end;

//===={IInternetProtocolRoot Interface}=========================================

function TEmbeddedWB.Start(szUrl: PWideChar; OIProtSink: IInternetProtocolSink;
   OIBindInfo: IInternetBindInfo; grfPI, dwReserved: DWORD): HRESULT; stdcall;
var
   iNeg: IHTTPNegotiate;
   szHeaders, szAdditionalHeaders: pWideChar;
   SrvProv: IServiceProvider;
begin
   FProtSink := OIProtSink;
   FBindInfo := OIBindInfo;

   (OIProtSink as iUnknown).QueryInterface(IServiceProvider, SrvProv);
   SrvProv.QueryService(IID_IHTTPNegotiate, IID_IHTTPNegotiate, iNeg);
   if Assigned(iNeg) then
      begin
         szHeaders := nil;
         szAdditionalHeaders := nil;
         iNeg.BeginningTransaction(szUrl, szHeaders, 0, szAdditionalHeaders);
      end;
   Result := INET_E_USE_DEFAULT_PROTOCOLHANDLER;
end;

function TEmbeddedWB.Terminate(dwOptions: DWORD): HRESULT; stdcall;
begin
   Result := S_OK;
end;

function TEmbeddedWB.Continue(const ProtocolData: TProtocolData): HRESULT;
begin
   Result := S_OK;
end;

function TEmbeddedWB.Abort(hrReason: HRESULT; dwOptions: DWORD): HRESULT; stdcall;
begin
   Result := E_NOTIMPL;
end;

function TEmbeddedWB.Suspend: HRESULT; stdcall;
begin
   Result := E_NOTIMPL;
end;

function TEmbeddedWB.Resume: HRESULT; stdcall;
begin
   Result := E_NOTIMPL;
end;

//===={IInternetProtocol Interface}=============================================

function TEmbeddedWB.LockRequest(dwOptions: DWORD): HRESULT; stdcall;
begin
   Result := S_OK;
end;

function TEmbeddedWB.Read(pv: Pointer; cb: ULONG; out cbRead: ULONG): HRESULT;
begin
   Result := S_OK;
end;

function TEmbeddedWB.Seek(dlibMove: LARGE_INTEGER; dwOrigin: DWORD;
   out libNewPosition: ULARGE_INTEGER): HRESULT;
begin
   Result := E_NOTIMPL;
end;

function TEmbeddedWB.UnlockRequest: HRESULT;
begin
   Result := S_OK;
end;

//=Print Options ===============================================================

procedure TPrintOptions.SetHTMLHeader(const Value: Tstrings);
begin
   FHTMLHeader.Assign(Value);
end;

//=Disable Errors ==============================================================

procedure TDisableErrors.SetfpExceptions(const Value: Boolean);
begin
  if not Value then begin
    Set8087CW($133F);
    FfpExceptions := False;
  end
  else
  begin
    Set8087CW(wSaved8087CW);
    FfpExceptions := True;
  end;
end;

//===DDE stuff  ================================================================
{$IFDEF USE_EwbDDE}
function TEmbeddedwb.DDETerminate(iwParam: WPARAM; ilParam: LPARAM): BOOL;
begin
   Result := PostMessage(THandle(iwParam), WM_DDE_TERMINATE, handle, 0);
end;

function TEmbeddedWB.DDEInitiate(iwParam: WPARAM; ilParam: LPARAM): LResult;
var
   dwThreadID: DWORD;
   dwProcessID: DWORD;
   hwndClient: Integer;
   aInApp, aInTopic, aOutApp, aOutTopic: ATOM;
   szInAppName, szInAppTopic: array[0..255] of Char;
begin
   FillChar(szInAppName, SizeOf(szInAppName), 0);
   FillChar(szInAppTopic, SizeOf(szInAppTopic), 0);
   if DontRespond then
      begin
         Result := 0;
         exit;
      end;
   hwndClient := THandle(iwParam);
   dwThreadID := GetWindowThreadProcessId(hwndClient, @dwProcessID);
   if (GetCurrentProcessId() <> dwProcessID) or (GetCurrentThreadID() <> dwThreadID) then
      begin
         Result := 0;
         exit;
      end;
   aInApp := LOWORD(ilParam);
   aInTopic := HIWORD(ilParam);
   GlobalGetAtomName(aInApp, szInAppName, SizeOf(szInAppName));
   GlobalGetAtomName(aInTopic, szInAppTopic, SizeOf(szInAppTopic));
   if szInAppName = HtmlFileApp then
      begin
         fHtmlCommand := True;
         aOutApp := GlobalAddAtom(PChar(HtmlFileApp));
         aOutTopic := GlobalAddAtom(PChar(HtmlFileTopic));
         if ((aOutApp <> 0) and (aOutTopic <> 0) and (aOutApp = aInApp) and (aOutTopic = aInTopic)) then
            SendMessage(hwndClient, WM_DDE_ACK, WPARAM(handle), MAKELPARAM(aOutApp, aOutTopic));
         if (aOutApp <> 0) then
            GlobalDeleteAtom(aOutApp);
         if (aOutTopic <> 0) then
            GlobalDeleteAtom(aOutTopic);
      end
   else
      begin
         fHtmlCommand := False;
         aOutApp := GlobalAddAtom(PChar(FoldersApp));
         aOutTopic := GlobalAddAtom(PChar(FoldersTopic));
         if ((aOutApp <> 0) and (aOutTopic <> 0) and (aOutApp = aInApp) and (aOutTopic = aInTopic)) then
            SendMessage(HWNDClient, WM_DDE_ACK, WPARAM(Handle), MAKELPARAM(aOutApp, aOutTopic));
         if (aOutApp <> 0) then
            GlobalDeleteAtom(aOutApp);
         if (aOutTopic <> 0) then
            GlobalDeleteAtom(aOutTopic);
      end;
   Result := 0;
end;

function TEmbeddedwb.DDEExecute(iwParam: WPARAM; ilParam: LPARAM): LResult;
var
   szFolder: string;
   szCommand: LPTSTR;
   uLo: PUINT;
   hgMem: HGLOBAL;
   ack: DDEACK;
   lpTemp: PUINT;
   uCommand: Cardinal;
   show: Integer;
   pidl: PITEMIDLIST;
   sei: TShellExecuteInfo;
   szTmp: string;
begin
   ulo := nil;
   if UnpackDDElParam(WM_DDE_EXECUTE, ilParam, uLo, @hgMem)
      then
      begin
         szCommand := GlobalLock(hgmem);
         ZeroMemory(@Ack, sizeof(ddeAck));
         if (szCommand <> nil) then
            begin
               if fHtmlCommand then
                  begin
                     szTmp := szCommand;
                     if Pos('"', szTmp) = 1 then
                        begin
                           Delete(szTmp, 1, 1);
                           szTmp := System.Copy(szTmp, 1, Pos('"', szTmp) - 1);
                        end;
                     Go(szTmp);
                     Ack.flags := 1;
                  end
               else
                  begin
                     uCommand := ParseDDECommand(szCommand, szFolder, pidl, Show);
                     case uCommand of
                        VIEW_COMMAND:
                           begin

                              if (szFolder <> '') then
                                 Go(szFolder)
                              else
                                 if (pidl <> nil) then
                                    NavigatePidl(pidl);
                              DisposePidl(pidl);
                              Ack.flags := 1;
                           end;
                        EXPLORE_COMMAND:
                           begin
                              DontRespond := True;
                              ZeroMemory(@sei, sizeof(SHELLEXECUTEINFO));
                              sei.cbSize := sizeof(SHELLEXECUTEINFO);
                              if szFolder <> '' then
                                 begin
                                    sei.fMask := SEE_MASK_CLASSNAME;
                                    sei.lpFile := Pchar(szFolder);
                                 end
                              else
                                 begin
                                    sei.fMask := SEE_MASK_IDLIST or SEE_MASK_CLASSNAME;
                                    sei.lpIDList := pidl;
                                 end;
                              sei.lpClass := 'folder';
                              sei.Wnd := 0;
                              sei.nShow := Show;
                              sei.lpVerb := 'explore';
                              ShellExecuteEx(@sei);
                              DontRespond := False;
                              DisposePidl(pidl);
                              Ack.flags := 1;
                           end;
                        FIND_COMMAND:
                           begin
                              DontRespond := True;
                              ZeroMemory(@sei, sizeof(SHELLEXECUTEINFO));
                              sei.cbSize := sizeof(SHELLEXECUTEINFO);
                              if (szFolder <> '')
                                 then
                                 begin
                                    sei.fMask := 0;
                                    sei.lpFile := PChar(szFolder);
                                 end
                              else
                                 begin
                                    sei.fMask := SEE_MASK_IDLIST;
                                    sei.lpIDList := pidl;
                                 end;
                              sei.wnd := 0;
                              sei.nShow := Show;
                              sei.lpVerb := 'find';
                              ShellExecuteEx(@sei);
                              DontRespond := False;
                              DisposePidl(pidl);
                              Ack.flags := 1;
                           end;
                     end;
                  end;
               GlobalUnlock(hgMem);
               lpTemp := @Ack;
               PostMessage(Thandle(iwParam),
                  WM_DDE_ACK,
                  WPARAM(handle),
                  ReuseDDElParam(ilParam, WM_DDE_EXECUTE, WM_DDE_ACK, lpTemp^, hgMem));
            end;
      end;
   Result := 0;
end;
  {$ENDIF}
//=== EmbeddedWB Events=========================================================
constructor TEmbeddedWB.Create(Owner: TComponent);
begin
   inherited;
  {---------------------------------------------}
   FAbout := EWB_INFO;
   FUserAgent := EWB_INFO;
  {---------------------------------------------}
   FPrintOptions := TPrintOptions.Create;
   FPrintOptions.Margins := TMargins.Create;
   FPrintOptions.FHTMLHeader := TStringlist.Create;
   FPrintOptions.FHTMLHeader.Add('<HTML></HTML>');
  {---------------------------------------------}
   FProxySettings := TProxySettings.Create;
   FProxySettings.FPort := 80;
  {---------------------------------------------}
   FShortCuts := TShortCuts.Create(Self);
  {---------------------------------------------}
   FDisableErrors := TDisableErrors.Create;
   FDisableErrors.FEnableDDE := True;
   FDisableErrors.FfpExceptions := True;
   FDisableErrors.FScriptErrorsSuppressed := True;
  {---------------------------------------------}
   FDialogBoxes := TDialogBoxes.Create;
   FDialogBoxes.FReplaceCaption := True;
   FDialogBoxes.FReplaceIcon := True;
  {---------------------------------------------}
   FVisualEffects := TVisualEffects.Create;
   FVisualEffects.FTextSize := 2;
  {---------------------------------------------}
   m_bWinXPSP2 := IsWinXPSP2OrLater;
   m_bResizing := not m_bWinXPSP2;
   FSearchText := '';
   FHTMLChar := #0;
   FTextRange := nil;
   FEnableMessageHandler:= True; 
end;

destructor TEmbeddedWB.Destroy;
begin
   FPrintOptions.HTMLHeader.Free;
   FPrintOptions.Margins.Free;
   FPrintOptions.Free;
   FShortcuts.Free;
   FDialogBoxes.Free;
   FDisableErrors.Free;
   FProxySettings.Free;
{$IFDEF USE_EwbTools}
   if (FVisualEffects.FTextSize <> 2) and (not (csDesigning in ComponentState)) then
      Zoom := 2;
{$ENDIF}
   FVisualEffects.Free;
   UnHook;
   FTextRange := nil;
   inherited;
end;

procedure TEmbeddedWB.LoadSettings;
begin
   if not (csDesigning in ComponentState) then
   begin
     Modified := False;
     RuntimeMeasure := GetRunTimeMeasure;
     FEnableMessageHandler := True;
     {$IFDEF USE_EwbDDE}
     GetDDEVariables;
     {$IFDEF DELPHI_6_UP}
     {$WARN SYMBOL_DEPRECATED OFF}
     {$ENDIF}
     DDEHWND := AllocateHWnd(DDEWndProc);
     {$IFDEF DELPHI_6_UP}
     {$WARN SYMBOL_DEPRECATED OFF}
    {$ENDIF} {$ENDIF}
     WindowProc := WndProc;
     CoInternetCreateSecurityManager(Self, SecurityManager, 0);
     CoInternetCreateZoneManager(Self, ZoneManager, 0);
     if FDisableErrors.FScriptErrorsSuppressed then
        ScriptErrorAction := eaContinue;
     Hook;
{$IFDEF USE_EwbTools}
         SetUserAgent;
         if (FProxySettings.FAutoLoadProxy) and (FProxySettings.FAddress <> '') then
            begin
               if FProxySettings.FUserName = '' then
                  FProxySettings.SetProxy(FUserAgent, FProxySettings.FAddress + ':' + IntToStr(FProxySettings.FPort))
               else
                  FProxySettings.SetProxy(FUserAgent, FProxySettings.FAddress, FProxySettings.FUserName,
                     FProxySettings.FUserName, FProxySettings.FPort);
            end;
         if FVisualEffects.FDisableSounds then
            begin
               DisableNavSound(True);
               bNavSound := True;
            end;
{$ENDIF}
      end
   else
      begin
         FPrintOptions.FMeasure := RunTimeMeasure;
         GetPrintValues;
      end; 
end;

procedure TEmbeddedWB.Loaded;
begin
   inherited Loaded;
   LoadSettings;
end;

procedure TEmbeddedWB.Hook;
begin
   if not bHook and not (csDesigning in ComponentState) then
      begin
         FParentForm := TForm(Owner);
         if (FParentForm <> nil) and (FParentForm.HandleAllocated) then
            begin
               FOldWindowProc := FParentForm.WindowProc;
               FParentForm.WindowProc := FormWndProc;
               bHook := True;
            end;
      end;
end;

procedure TEmbeddedWB.UnHook;
begin
   if bHook and not (csDesigning in ComponentState) then
      begin
         if (FParentForm <> nil) and (FParentForm.HandleAllocated) then
            FParentForm.WindowProc := FOldWindowProc;
         FParentForm := nil;
         bHook := False;
      end;
end;

{$IFDEF USE_EwbDDE}
procedure TEmbeddedWB.DDEWndProc(var AMsg: Messages.TMessage);
begin
   with AMsg do
      if (Msg = WM_DDE_INITIATE) and FDisableErrors.FEnableDDE //and FEnableDDE
         then
         DDEInitiate(WParam, LParam)
      else
         Result := DefWindowProc(DDEHWND, Msg, WParam, LParam);
end;
 {$ENDIF}
function TEmbeddedWB.GetModified: Boolean;
begin
   Result := FModified;
end;

procedure TEmbeddedWB.SetModified(Value: Boolean);
var
   Doc: IHTMLDocument2;
begin
   if ((not FModified) and (READYSTATE = READYSTATE_COMPLETE)) then
      begin
         Doc := Document as IHTMLDocument2;
         if doc <> nil then
            FModified := Doc.QueryCommandEnabled('Undo');
      end;
end;

procedure TEmbeddedWB.SetAbout(Value: string);
begin
   Exit;
end;

function TEmbeddedWB.VariantIsObject(const Value: OleVariant): Boolean;
begin
   Result := (VarType(Value) = varDispatch);
end;

procedure TEmbeddedWB.FormWndProc(var AMsg: Messages.TMessage);
var
   TxtLength: Integer;
   PopHandle: Integer;
   DlgName: string;
   Msg: TWMActivate;
begin
   if AMsg.Msg = WM_ACTIVATE then
      begin
         Msg := TWMActivate(AMsg);
         if Msg.Active = 0 then
            begin
               PopHandle := Msg.ActiveWindow;
               SetLength(DlgName, 80);
               SetLength(DlgName, GetClassName(PopHandle, PChar(DlgName), Length(DlgName)));
               if (DlgName = '#32770') or (DlgName = 'Internet Explorer_TridentDlgFrame') then
                  begin
                     if FDialogBoxes.FDisableAll then
                        SendMessage(PopHandle, WM_CLOSE, 0, 0);
                     if FDialogBoxes.FReplaceIcon then
                        SendMessage(PopHandle, WM_SETICON, ICON_SMALL, Forms.Application.Icon.Handle);
                     if FDialogBoxes.FReplaceCaption then
                        begin
                           if FDialogBoxes.FNewCaption = '' then
                              FDialogBoxes.FNewCaption := 'Web Browser';
                           TxtLength := GetWindowTextLength(PopHandle);
                           SetLength(DlgName, TxtLength + 1);
                           GetWindowText(PopHandle, PChar(DlgName), TxtLength + 1);
                           DlgName := StringReplace(DlgName, 'Microsoft ', '', []);
                           DlgName := StringReplace(DlgName, 'Internet Explorer',
                                                       FDialogBoxes.FNewCaption, []);
                           if AnsiPos(FDialogBoxes.FNewCaption, DlgName) = 0 then
                              DlgName := FDialogBoxes.FNewCaption + ':  ' + DlgName;
                          SetWindowText(PopHandle, PChar(DlgName));
                        end;
                     if FDisableErrors.FScriptErrorsSuppressed then
                        begin
                          if (AnsiPos('SCRIPT', AnsiUpperCase(DlgName)) <> 0) then
                            begin
                              PostMessage(PopHandle, WM_LBUTTONDOWN, 0 ,0);
                              PostMessage(PopHandle, WM_LBUTTONUP, 0, 0);
                              SendMessage(PopHandle, WM_CLOSE , 0, 0);
                              Forms.Application.ProcessMessages;
                              Exit;
                           end;
                          if(AnsiPos('ERROR', AnsiUpperCase(DlgName)) <> 0) then
                            begin
                              DestroyWindow(PopHandle);
                             Exit;
                           end;
                        end;
                     if FPrintOptions.FEnabled then
                        begin
                           bPrintOptionsEnable := True;
                           if InvokingPageSetup then
                              begin
                                 InvokingPageSetup := False;
                                 if PrintingWithOptions then
                                    begin
                                       SetWindowPos(0, 0, -600, 0, 0, 0, 0); //SetWindowPos(Wnd, 0, -600, 0, 0, 0, 0);
                                       PrintingWithOptions := False;
                                    end;
                                 if FPrintOptions.FOrientation = poPortrait then
                                    SendDlgItemMessage(PopHandle, $0420, BM_CLICK, 0, 0)
                                 else
                                    SendDlgItemMessage(PopHandle, $0421, BM_CLICK, 0, 0);
                                 SetDlgItemText(PopHandle, $1FD3, PChar(FPrintOptions.FHeader));
                                 SetDlgItemText(PopHandle, $1FD5, PChar(FPrintOptions.FFooter));
                                 SetDlgItemText(PopHandle, $0483, PrintMarginStr(FPrintOptions.FMargins.FLeft));
                                 SetDlgItemText(PopHandle, $0484, PrintMarginStr(FPrintOptions.FMargins.Ftop));
                                 SetDlgItemText(PopHandle, $0485, PrintMarginStr(FPrintOptions.FMargins.FRight));
                                 SetDlgItemText(PopHandle, $0486, PrintMarginStr(FPrintOptions.FMargins.FBottom));
                                 if (Win32Platform = VER_PLATFORM_WIN32_NT) and (Win32MajorVersion > 4) then
                                    PostMessage(FindWindowEx(PopHandle, 0, PChar('Button'), nil), BM_CLICK, 0, 0) //Win2000
                                 else
                                    SendDlgItemMessage(PopHandle, 1, BM_CLICK, 0, 0);
                              end;
                        end;
                  end;
               if not PrintingWithOptions and (PopHandle <> 0) and Assigned(FOnShowDialog) then
                  FOnShowDialog(Self, PopHandle);
            end;
      end;
   FOldWindowProc(AMsg);
end;

procedure TEmbeddedWB.WndProc(var message: TMessage);
var
   bClose: Boolean;
begin
   inherited WndProc(Message);
   if FEnableMessageHandler and (Message.Msg = CN_BASE + WM_KEYDOWN) and
     (Message.WParam = VK_RETURN) then
      Message.Result := 0;
   with message do
      begin
         case Msg of
            WM_CLOSE:
               begin
                  bClose := True;
                  if Assigned(FOnCloseQuery) then
                     FOnCloseQuery(Self, bClose);
               end;
            WM_SIZE:
               if (not ((not Self.Focused) and (Message.Msg = CM_DIALOGKEY))) then
                  begin
                     m_bResizing := False;
                     m_bResizing := not m_bWinXPSP2; // must be set in constructor
                  end;
            WM_WINDOWPOSCHANGING:
               begin
                  if m_bResizing and ((PWindowPos(lParam)^.flags and (SWP_NOMOVE or SWP_NOSIZE)) > 0) then
                     begin
                        if ((PWindowPos(lParam)^.flags and SWP_NOMOVE) = 0) then
                           begin
                              PWindowPos(lParam)^.flags := PWindowPos(lParam)^.flags or SWP_NOMOVE;
                              if Assigned(OnMove) then
                                 OnMove(Self, PWindowPos(lParam)^.x, PWindowPos(lParam)^.y);
                           end;

                        if ((PWindowPos(lParam)^.flags and SWP_NOSIZE) = 0) then
                           begin
                              PWindowPos(lParam)^.flags := PWindowPos(lParam)^.flags or SWP_NOSIZE;
                              if Assigned(OnResize) then
                                 OnResize(Self, PWindowPos(lParam)^.cx, PWindowPos(lParam)^.cy);
                           end;
                     end;
              end;
   {$IFDEF USE_EwbDDE}
            WM_DDE_EXECUTE  : DDEExecute(wParam, lparam);
            WM_DDE_TERMINATE: DDETerminate(wparam, lparam);
   {$ENDIF}
         end;
      end;
end;

//-------------------------------

function TEmbeddedWB.ImportCertFile(AFileName, AStoreType: string): Boolean;
var
   f: file; //by Ray
   encCert: PByte;
   encCertLen: DWORD;
   store: HCERTSTORE;
   context: PCCERT_CONTEXT;
   n: PCCERT_CONTEXT;
   encType: DWORD;
begin
   Result := False;
   if FileExists(AFileName) then
      begin
         AssignFile(f, AFileName);
         reset(f, 1);
         encCertLen := FileSize(f);
         GetMem(encCert, encCertLen);
         BlockRead(f, encCert^, encCertLen);
         CloseFile(f);
         try
            encType := PKCS_7_ASN_ENCODING or X509_ASN_ENCODING;
            context := CertCreateCertificateContext(encType, encCert, encCertLen);
            if context = nil then
               begin
                  exit;
               end;
            store := CertOpenSystemStore(0, PChar(AStoreType));
            if store = nil then
               begin
                  exit;
               end;
            n := nil;
            CertAddCertificateContextToStore(store, context,
               CERT_STORE_ADD_REPLACE_EXISTING, n);
            CertCloseStore(store, 0);
            CertFreeCertificateContext(context);
            Result := True;
         finally
            FreeMem(encCert, encCertLen);
         end;
      end;
end;

procedure TEmbeddedWB.Go(Url: string);
var
   _URL, Flags, TargetFrameName, PostData, Headers: OleVariant;
begin
   _URL := Url;
   Flags := 0;
   TargetFrameName := 0;
   Postdata := 0;
   Headers := 0;
   if (Trim(_URL) <> '') then
      Navigate2(_URL, Flags, TargetFrameName, PostData, Headers);
end;

function TEmbeddedWB.DocumentLoaded: Boolean;
var
   iDoc: IHtmlDocument2;
begin
   Result := False;
   if Document <> nil then
      begin
         ControlInterface.Document.QueryInterface(IHtmlDocument2, iDoc);
         Result := Assigned(iDoc);
      end;
end;

function TEmbeddedWB.GetDocument: IHtmlDocument2;
begin
   Wait();
   Result := Self.Document as IHtmlDocument2;
   if Result = nil then
      raise Exception.Create('Unable to Load Docuemnt');
end;

function TEmbeddedWB.SaveToFile(const FileName: string): HRESULT;
begin
   Wait();
   if Assigned(Document) then
      begin
         Result := SaveDocToFile(Document, FileName);
      end
   else
      Result := S_False;
end;

function TEmbeddedWB.SaveToStream(AStream: TStream): HRESULT;
begin
   Wait();
   if Assigned(Document) then
      Result := SaveDocToStream(Document, AStream)
   else
      Result := S_False;
end;

function TEmbeddedWB.SaveToStrings(AStrings: TStrings): HRESULT;
begin
   Wait();
   if Assigned(document) then
      Result := SaveDocToStrings(Document, AStrings)
   else
      Result := S_False;
end;

function TEmbeddedWB.SaveFrameToFile(FrameNo: Integer; const FName: string): HRESULT;
var
   Iw: IWebbrowser2;
   PFile: IPersistFile;
begin
   iw := Getframe(frameNo);
   if (iw <> nil) and assigned(iw.Document) then
      begin
         PFile := iw.Document as IPersistFile;
         Result := PFile.Save(StringToOleStr(FName), False);
      end
   else
      Result := S_False;
end;

function TEmbeddedWB.SaveFrameToStream(FrameNo: Integer; AStream: TStream): HRESULT;
var
   iw: IWebbrowser2;
begin
   Result := S_False;
   iw := Getframe(frameNo);
   if (iw <> nil) and assigned(iw.Document) then
      Result := SaveDocToStream(iw.Document, AStream)
end;

function TEmbeddedWB.SaveFrameToStrings(FrameNo: Integer; AStrings: TStrings): HRESULT;
var
   iw: Iwebbrowser2;
begin
   Result := S_False;
   iw := Getframe(frameNo);
   if (iw <> nil) and assigned(iw.Document) then
      Result := SaveDocToStrings(iw.Document, AStrings);
end;

function TEmbeddedWB.LoadFromStrings(const AStrings: TStrings): HRESULT;
var
   M: TMemoryStream;
begin
   if not Assigned(document) then
      AssignEmptyDocument;
   M := TMemoryStream.Create;
   try
      AStrings.SaveToStream(M);
      Result := LoadFromStream(M);
   except
      Result := S_False;
   end;
   M.free;
end;

function TEmbeddedWB.LoadFromStrings(const AStrings: TStrings; AddHtmlTags: Boolean): HRESULT;

   function AnsiSameStr(const S1, S2: string): Boolean;
   begin
      Result := AnsiCompareStr(S1, S2) = 0;
   end;

   function AnsiStartsStr(const ASubText, AText: string): Boolean;
   begin
      Result := AnsiSameStr(ASubText, System.Copy(AText, 1, Length(ASubText)));
   end;
var
   M: TMemoryStream;
   stn: TStrings;
begin
   if not Assigned(document) then
      AssignEmptyDocument;
   M := TMemoryStream.Create;
   try
      if AddHtmlTags and not AnsiStartsStr('<HTML>', UpperCase(AStrings.GetText)) then
         begin
            stn := TStringList.Create;
            with stn do
               begin
                  Add('<html>');
                  Add('<body>');
                  Add('<body bgcolor="#ffffff">');
                  AddStrings(AStrings);
                  Add('</body>');
                  Add('</html>');
                  SaveToStream(M);
               end;
         end
      else
         AStrings.SaveToStream(M);
      Result := LoadFromStream(M);
   except
      Result := S_False;
   end;
   M.free;
end;

function TEmbeddedWB.LoadFromStream(const AStream: TStream): HRESULT;
begin
   if not Assigned(Document) then
      AssignEmptyDocument;
   AStream.seek(0, 0);
   Result := (Document as IPersistStreamInit).Load(TStreamadapter.Create(AStream));
end;

function TEmbeddedWB.LoadFrameFromStrings(Frameno: Integer; const AStrings: TStrings): HRESULT;
var
   iw: IWebbrowser2;
   M: TMemoryStream;
begin
   Result := S_False;
   iw := GetFrame(Frameno);
   if (iw <> nil) and assigned(iw.document) then
      begin
         M := TMemoryStream.Create;
         try
            AStrings.SaveToStream(M);
            M.seek(0, 0);
            Result := (iw.Document as IPersistStreamInit).Load(TStreamadapter.Create(M));
         except
            Result := S_False;
         end;
         M.free;
      end;
end;

function TEmbeddedWB.LoadFrameFromStream(FrameNo: Integer; AStream: TStream): HRESULT;
var
   iw: IWebbrowser2;
begin
   Result := S_False;
   iw := Getframe(frameNo);
   if (iw <> nil) then
      if Assigned(iw.Document) then
         begin
            AStream.seek(0, 0);
            Result := (iw.Document as IPersistStreamInit).Load(TStreamadapter.Create(AStream));
         end;
end;

procedure TEmbeddedWB.AssignEmptyDocument;
begin
   Go('about:blank');
end;

procedure TEmbeddedWB.Wait;
begin
   while ReadyState <> READYSTATE_COMPLETE do
      Forms.Application.ProcessMessages;
end;

procedure TEmbeddedWB.Wait2;
begin
   while Busy do
      Forms.Application.ProcessMessages;
end;

procedure TEmbeddedWB.NavigatePidl(pidl: PItemIdList);
var
   VaEmpty, vaPidl: OleVariant;
   psa: PSafeArray;
   cbData: UINT;
begin
   cbdata := GetPidlSize(pidl);
   psa := SafeArrayCreateVector(VT_UI1, 0, cbData);
   if (psa <> nil) then
      begin
         CopyMemory(psa.pvData, pidl, cbData);
         VariantInit(vaPidl);
         TVariantArg(vaPidl).vt := VT_ARRAY or VT_UI1;
         TVariantArg(vaPidl).parray := psa;
         Navigate2(vaPidl, vaEmpty, vaEmpty, vaEmpty, vaEmpty);
         VariantClear(vaPidl);
      end;
end;

function TEmbeddedWB.GetFrame(FrameNo: Integer): IWebbrowser2;
var
   OleContainer: IOleContainer;
   Enum: ActiveX.IEnumUnknown;
   Unk: IUnknown;
   Fetched: PLongint;
begin
   wait();
   if Assigned(document) then
      begin
         Fetched := nil;
         OleContainer := Document as IOleContainer;
         OleContainer.EnumObjects(OLECONTF_EMBEDDINGS, Enum);
         Enum.Skip(FrameNo);
         Enum.Next(1, Unk, Fetched);
         Result := Unk as IWebbrowser2;
      end
   else
      Result := nil;
end;

procedure TEmbeddedWB.GetPrintValues;
var
   S: string;
   Reg: TRegistry;

   function ReadMargin(key: string): Real;
   begin
      S := Reg.ReadString(key);
      if S = '' then
         S := '0.750000'; // <-- default margin value  by takeru_tk_81
      S := StringReplace(S, ' ', '', [rfReplaceAll]);
      if DecimalSeparator <> '.' then
         S := StringReplace(S, '.', DecimalSeparator, []);
      if PrintOptions.Measure = mMetric then
         Result := StrToFloat(S) * InchToMetric
      else
         Result := StrToFloat(S);
   end;

begin
   Reg := TRegistry.Create;
   try
      with Reg do
         begin
            RootKey := HKEY_CURRENT_USER;
            if OpenKey('Software\Microsoft\Internet Explorer\PageSetup', False) then
               begin
                  PrintOptions.Header := Readstring('header');
                  PrintOptions.Footer := ReadString('footer');
                  PrintOptions.Margins.Left := ReadMargin('margin_left');
                  PrintOptions.Margins.Right := ReadMargin('margin_right');
                  PrintOptions.Margins.Top := ReadMargin('margin_top');
                  PrintOptions.Margins.Bottom := ReadMargin('margin_bottom');
               end;
            Reg.Free;
         end;
   except
      MessageDlg('Error while getting page print values from the registry!', mtError, [mbOK], 0);
   end;
end;

function TEmbeddedWB.PrintMarginStr(M: Real): PChar;
var
   S: string;
begin
   if printOptions.Measure <> RuntimeMeasure
      then
      begin
         if RuntimeMeasure = mMetric then
            s := FloatToStr(M * InchToMetric)
         else
            s := FloatToStr(M / InchToMetric);
         Result := PChar(S);
      end
   else
      Result := PChar(FloatToStr(M));
end;

function TEmbeddedWB.DesignMode: Boolean;
var
   HTMLDocument2: IHTMLDocument2;
   Status: string;
begin
   Result := False;
   HTMLDocument2 := (Document as IHTMLDocument2);
   if HTMLDocument2 <> nil then
      begin
         Status := HTMLDocument2.get_designMode;
         if Status = 'On' then
            begin
               HTMLDocument2.designMode := 'Off';
               Result := False;
            end
         else
            begin
               HTMLDocument2.designMode := 'On';
               Result := True;
            end;
      end;
end;

procedure TEmbeddedWB.Copy;
var
   vaIn, vaOut: Olevariant;
begin
   InvokeCmd(False, OLECMDID_COPY, OLECMDEXECOPT_DODEFAULT, vaIn, vaOut);
end;

procedure TEmbeddedWB.Paste;
var
   vaIn, vaOut: Olevariant;
begin
   InvokeCmd(False, OLECMDID_PASTE, OLECMDEXECOPT_DODEFAULT, vaIn, vaOut);
end;

procedure TEmbeddedWB.Cut;
var
   vaIn, vaOut: Olevariant;
begin
   InvokeCmd(False, OLECMDID_CUT, OLECMDEXECOPT_DODEFAULT, vaIn, vaOut);
end;

procedure TEmbeddedWB.SelectAll;
var
   vaIn, vaOut: OleVariant;
begin
   InvokeCmd(False, OLECMDID_SELECTALL, OLECMDEXECOPT_DODEFAULT, vaIn, vaOut);
end;

procedure TEmbeddedWB.RefreshFrame(FrameNumber: Integer);
var
   OleContainer: IOleContainer;
   Enum: ActiveX.IEnumUnknown;
   Unk: IUnknown;
   Fetched: PLongint;
begin
   wait();
   if Assigned(document) then
      begin
         Fetched := nil;
         OleContainer := Document as IOleContainer;
         OleContainer.EnumObjects(OLECONTF_EMBEDDINGS, Enum);
         Enum.Skip(FrameNumber);
         Enum.Next(1, Unk, Fetched);
         (Unk as IWebbrowser2).Refresh;
      end
end;

procedure TEmbeddedWB.InvokeCMD(InvokeIE: Boolean; Value1, Value2: Integer; var vaIn, vaOut: OleVariant);
const
   PGUIDs: array[Boolean] of PGUID = (nil, @CLSID_WebBrowser);
begin
   InvokeCommand(PGUIDs[InvokeIE], Value1, Value2, vaIn, vaOut);
end;

procedure TEmbeddedWB.InvokeIEServerCommand(Cmd: Integer);
begin
   SendMessage(Handle, WM_COMMAND, Cmd, 0);
end;

function TEmbeddedWB.GetIEHomePage: string;
var
   HomePage: string;
begin
   with TRegistry.Create do
      try
         RootKey := HKEY_CURRENT_USER;
         OpenKey('\Software\Microsoft\Internet Explorer\Main', False);
         HomePage := ReadString('Start Page');
         CloseKey;
      finally
         Free;
      end;
   Result := HomePage;
end;

function TEmbeddedWB.LoadFromString(const S: string): HRESULT;
var
   Strings: TStringList;
begin
   Strings := TStringList.Create;
   try
      Strings.Text := S;
      Result := LoadFromStrings(Strings);
   finally
      FreeAndNil(Strings);
   end;
end;

function TEmbeddedWB.LoadFromFile(const FileName: string): HRESULT;
var
   Stream: TStream;
begin
   Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
   try
      Result := LoadFromStream(Stream);
   finally
      Stream.Free;
   end;
end;

function TEmbeddedWB.FilterPopupMenu: Boolean;
begin
   Result := inherited FilterPopupMenu or (DisabledPopupMenuItems <> []);
end;

procedure TEmbeddedWB.DoFilterPopupMenu(ID: DWORD; Menu: HMENU; const Context: IDispatch);
const
   cmds: array[TIEPopupMenuItem] of UINT = (
      IDM_BACK, //rcsBack
      IDM_FORWARD, //rcsForward
      IDM_SAVEBACKGROUND, //rcsSavePageBkg
      IDM_SETASBACKGROUND, //rcsSetAsBkg
      IDM_COPYBACKGROUND, //rcsCopyBkg
      IDM_SETASDESKTOPITEM, //rcsSetAsDeskT
      IDM_SELECTALL, //rcsSelectAll
      IDM_PASTE, //rcsPaste
      IDM_CREATESHORTCUT, //rcsCreateSC
      IDM_ADDTOFAVOURITES, //rcsAddToFav
      IDM_ENCODING, //rcsEncoding
      IDM_REFRESH, //rcsRefresh
      IDM_VIEWSOURCE, //rcsViewSource
      IDM_PROPERTIES, //rcsProperties
      IDM_PRINT, //rcsPrint
      IDM_OPENINNEWWINDOW, //rcsOpenNWindow
      IDM_OPENLINK //rcsOpenLink
      );
var
   I: TIEPopupMenuItem;
begin
   inherited;
   for I := Low(TIEPopupMenuItem) to High(TIEPopupMenuItem) do
      if I in DisabledPopupMenuItems then
         DeleteMenu(Menu, cmds[I], MF_BYCOMMAND);
end;

class function TEmbeddedWB.GetIEHandle(WebBrowser: TEmbeddedWB; ClassName: string): HWND;
begin
   Result := WebBrowser.GetIEWin(ClassName);
end;

procedure TEmbeddedWB.ShowImportExportFavoritesAndCookies;
begin
   SendMessage(Handle, WM_COMMAND, ID_IE_FILE_IMPORTEXPORT, 0);
end;

function TEmbeddedWB.GetHostInfo(var pInfo: TDOCHOSTUIINFO): HRESULT;
begin
   Result := inherited GetHostInfo(pInfo);
   if (pInfo.chHostCss = nil) and (HostCSS <> '') then
      pInfo.chHostCss := TaskAllocWideString(HostCSS);
   if (pInfo.chHostNS = nil) and (HostNS <> '') then
      pInfo.chHostNS := TaskAllocWideString(fHostNS);
end;
// -----------------------------------------------------------------------------
// EwbTools
// -----------------------------------------------------------------------------

//Document and Frame -----------------------------------------------------------

{$IFDEF USE_EwbTools}
function TEmbeddedWB.GetWordAtCursor(const X, Y: Integer): string;
var
   Selection: IHTMLSelectionObject;
   Range: IHTMLTxtRange;
begin
   Result := '';
   Selection := (GetDocument as IHTMLDocument2).selection;
   if Assigned(Selection) then
      begin
         Range := Selection.createRange as IHTMLTxtRange;
         Range.moveToPoint(X, Y);
         Range.moveStart('word', -1);
         Range.moveEnd('word', 1);
         Result := Trim(Range.text);
      end;
end;

function TEmbeddedWB.SearchNextText(const Value: string; Direction: TSearchDirections = sdDown;
   AutoSelect: Boolean = True): TSearchResults;
const
   ADirection: array[TSearchDirections] of Shortint = (+1, -1);
begin
   Result := [srNotFound];
   if AnsiCompareText(Value, FSearchText) <> 0 then
      begin
         FTextRange := nil;
         FSearchText := Value;
         FHTMLChar := #0;
      end;
  //
   if FSearchText = '' then
      Exit;
  //
   if FTextRange = nil
      then
      FTextRange := (GetDocument.body as IHTMLBodyElement).createTextRange;
  //
   if FHTMLChar <> #0 then
      begin
         if FHTMLChar <> Char(Ord(Direction) + 1) then
            begin
               FTextRange.move('character', 0);
            end
         else
            case Direction of
               sdDown: FTextRange.move('character', 1);
               sdUp: FTextRange.move('character', -1);
            end;
      end
   else
      begin
         if FLastDirection <> Direction then
            case FLastDirection of
               sdDown: FTextRange.move('character', -1);
               sdUp: FTextRange.move('character', 1);
            end;
      end;
  //
   if FTextRange.findText(FSearchText, ADirection[Direction], 0) then
      begin
         FTextRange.scrollIntoView(True);
         if AutoSelect then
            FTextRange.select;
         FHTMLChar := Char(Ord(Direction) + 1);
         Result := [srFound];
      end
   else
      FHTMLChar := #0;
   if (FLastDirection = Direction) and (FHTMLChar = #0)
      then
      Include(Result, srEndOf);
   FLastDirection := Direction;
end;

procedure TEmbeddedWB.PrintPreviewFromTemplate(const TemplateFileName: string);
var
   OleCommandTarget: IOleCommandTarget;
   ParamIn: OleVariant;
begin
   Document.QueryInterface(IID_IoleCommandTarget, OLECOMMANDTARGET);
   ParamIn := TemplateFileName;
   OleCommandTarget.Exec(
      nil,
      OLECMDID_PRINTPREVIEW,
      OLECMDEXECOPT_PROMPTUSER,
      ParamIn,
      EmptyParam
      );
end;

procedure TEmbeddedWB.ScrollToIDEx(ID: string);
var
   Doc: IHTMLDocument3;
   Elem: IHTMLElement;
   RV: IHTMLRect;
begin
   Doc := GetDocument as IHTMLDocument3;
   Elem := Doc.getElementById('11');
   if Assigned(Elem) then
      begin
         RV := (Elem as IHTMLElement2).getBoundingClientRect;
         GetDocument.parentWindow.scrollBy(RV.left, RV.top);
      end;
end;

procedure TEmbeddedWB.ScrollToID(ID: Integer);
var
   ACollection: IHTMLElementCollection;
   Elem: IHTMLElement;
   Match: IHTMLElement2;
   I: Integer;
   S: string;
   RV: IHTMLRect;
begin
   ACollection := GetDocument.all;
   if Assigned(ACollection) then
      begin
         Match := nil;
         S := IntToStr(ID);
         for I := 0 to ACollection.length - 1 do
            begin
               Elem := ACollection.item(I, '') as IHTMLElement;
               if Assigned(Elem) and (Elem.id = S) then
                  begin
                     Match := Elem as IHTMLElement2;
                     Break;
                  end;
            end;
         if Assigned(Match) then
            begin
               RV := Match.getBoundingClientRect;
               GetDocument.parentWindow.scrollBy(RV.left, RV.top);
            end;
      end;
end;

function TEmbeddedWB.DocumentSource: string;
var
   Strings: TStringList;
begin
   Strings := TStringList.Create;
   try
      EwbTools.ViewPageSourceHTMLToStrings(OleObject, Document, Strings);
      Result := Strings.Text;
   finally
      FreeAndNil(Strings);
   end;
end;

function TEmbeddedWB.GetSelLength: Integer;
var
   Sel: IHTMLSelectionObject;
   TxtRange: IHTMLTxtRange;
begin
   Result := 0;
   Sel := GetDocument.selection;
   if Assigned(Sel) then
      begin
         TxtRange := Sel.createRange as IHTMLTxtRange;
         if Assigned(TxtRange) then
            Result := Length(TxtRange.Text);
      end;
end;

function TEmbeddedWB.DocumentSourceText: string;
var
   Strings: TStringList;
begin
   Strings := TStringList.Create;
   try
      EwbTools.ViewPageSourceTextToStrings(OleObject, Document, Strings);
      Result := Strings.Text;
   finally
      FreeAndNil(Strings);
   end;
end;

function TEmbeddedWB.GetSelText: WideString;
var
   Sel: IHTMLSelectionObject;
   TxtRange: IHTMLTxtRange;
begin
   Result := '';
   Sel := GetDocument.selection;
   if Assigned(Sel) then
      begin
         TxtRange := Sel.createRange as IHTMLTxtRange;
         if Assigned(TxtRange) then
            Result := TxtRange.Text;
      end;
end;

function TEmbeddedWB.GetSelTextHTML: WideString;
var
   Sel: IHTMLSelectionObject;
   TxtRange: IHTMLTxtRange;
begin
   Result := '';
   Sel := GetDocument.selection;
   if Assigned(Sel) then
      begin
         TxtRange := Sel.createRange as IHTMLTxtRange;
         if Assigned(TxtRange) then
            Result := TxtRange.htmlText;
      end;
end;

function TEmbeddedWB.AddHtmlToAboutBlank(StringToHtml: string): Boolean;
begin
   Result := EwbTools.AddHtmlToAboutBlank(Self, StringToHtml);
end;

function TEmbeddedWB.GetFrameFromDocument(SourceDoc: IHtmlDocument2;
   FrameNo: Integer): IWebBrowser2; //By Aladin
begin
   Wait();
   Result := EwbTools.GetFrameFromDocument(SourceDoc, FrameNo)
end;

function TEmbeddedWB.FrameCount: Longint;
begin
   Wait();
   Result := EwbTools.FrameCount(Document);
end;

function TEmbeddedWB.FrameCountFromDocument(SourceDoc:
   IHtmlDocument2): Integer; //By Aladin
begin
   Wait();
   Result := EwbTools.FrameCountFromDocument(SourceDoc);
end;

//Document Operations ----------------------------------------------------------

procedure TEmbeddedWB.ScrollToTop;
begin
   Wait();
   EwbTools.ScrollToTop(OleObject);
end;

procedure TEmbeddedWB.ScrollToBottom;
begin
   Wait();
   EwbTools.ScrollToBottom(OleObject);
end;

procedure TEmbeddedWB.ScrollToPosition(X, Y: Integer);
begin
   Wait();
   EwbTools.ScrollToPosition(OleObject, X, Y);
end;

function TEmbeddedWB.SetCharartersSet(const ACharactersSet: string): Boolean;
begin
   Wait();
   Result := EwbTools.SetCharartersSet(Self, Document, ACharactersSet);
end;

function TEmbeddedWB.GetCookie: string;
begin
   Wait();
   Result := Self.Cookie;
end;

procedure TEmbeddedWB.GetThumbnail(var Image: TImage);
begin
   EwbTools.GetThumbnail(Application, Image)
end;

function TEmbeddedWB.GetBmpFromBrowser(FileName: string): Boolean;
begin
   Result := EwbTools.GetBmpFromBrowser(Document, Self.Handle, Self.Width, Self.Height, FileName);
end;

function TEmbeddedWB.GetJPEGfromBrowser(FileName: string; SourceHeight, SourceWidth,
   TargetHeight, TargetWidth: Integer): Boolean;
begin
   Result := EwbTools.GetJPEGfromBrowser(Document, ControlInterface, FileName, SourceHeight, SourceWidth, TargetHeight, TargetWidth);
end;

//View Document Fields/Properties/Images ---------------------------------------

procedure TEmbeddedWB.ViewPageFieldsToStrings(FieldList: TStrings);
begin
   EwbTools.ViewPageFieldsToStrings(OleObject, FieldList);
end;

procedure TEmbeddedWB.ViewPagePropertiesToStrings(PropertiesList: TStrings);
begin
   Wait();
   EwbTools.ViewPagePropertiesToStrings(OleObject, Document, PropertiesList);
end;

procedure TEmbeddedWB.ViewPageSourceText;
begin
   EwbTools.ViewPageSourceText(OleObject, Document);
end;

procedure TEmbeddedWB.ViewPageSourceTextToStrings(TextList: TStrings);
begin
   Wait();
   EwbTools.ViewPageSourceTextToStrings(OleObject, Document, TextList);
end;

procedure TEmbeddedWB.ViewPageSourceHTMLToStrings(HtmlList: TStrings);
begin
   Wait();
   EwbTools.ViewPageSourceHTMLToStrings(OleObject, Document, HtmlList);
end;

procedure TEmbeddedWB.ViewPageLinksToStrings(LinksList: TStrings);
begin
   EwbTools.ViewPageLinksToStrings(OleObject, LinksList);
end;

procedure TEmbeddedWB.ViewPageImagesToStrings(ImagesList: TStrings);
begin
   EwbTools.ViewPageImagesToStrings(OleObject, ImagesList);
end;

procedure TEmbeddedWB.LoadFromImage(Image: TImage);
begin
   EwbTools.LoadFromImage(Self, Image);
end;

//Printing ---------------------------------------------------------------------

procedure TEmbeddedWB.Print;
begin
   Wait();
   EwbTools.Print(ControlInterface, FPrintOptions.HideSetup);
end;

procedure TEmbeddedWB.PrintWithOptions;
begin
   Wait();
   bPrintOptionsEnable := True;
   EwbTools.PrintWithOptions(ControlInterface, Document, True, FPrintOptions.FEnabled, FPrintOptions.HideSetup, InvokingPageSetup);
end;

procedure TEmbeddedWB.PrintPreview;
begin
   EwbTools.PrintPreview(ControlInterface);
end;

procedure TEmbeddedWB.PrintPreviewExtended(nCMDShow: Integer);
begin
   bPrintOptionsEnable := True;

   EwbTools.PrintPreviewExtended(ControlInterface, nCMDShow, FPrintOptions.HideSetup);
end;

procedure TEmbeddedWB.PageSetup(UsePrintOptions: Boolean);
begin
   Wait();
   bPrintOptionsEnable := True;  
   EwbTools.PageSetup(Document, UsePrintOptions, FPrintOptions.FEnabled, InvokingPageSetup);
end;

procedure TEmbeddedWB.PrintSetup;
begin
   Wait();
   EwbTools.PrintSetup(ControlInterface, FPrintOptions.HideSetup);
end;

//Dialogs ---------------------------------------------------------------------

procedure TEmbeddedWB.OpenDialog;
begin
   EwbTools.OpenDialog(Self, Self);
end;

procedure TEmbeddedWB.SaveDialog;
begin
   EwbTools.SaveDialog(Document);
end;

function TEmbeddedWB.SaveDialogEx: string;
begin
   Result := EwbTools.SaveDialog(Self, Self);
end;

procedure TEmbeddedWB.ShowInternetOptions;
begin
   EwbTools.ShowInternetOptions(Document);
end;

procedure TEmbeddedWB.ShowPageProperties;
begin
   EwbTools.ShowPageProperties(Document);
end;

procedure TEmbeddedWB.ShowOrganizeFavorites;
begin
   EwbTools.ShowOrganizeFavorites(Handle);
end;

procedure TEmbeddedWB.ShowFindDialog;
begin
   EwbTools.ShowFindDialog(Document)
end;

procedure TEmbeddedWB.SaveImagesDialog;
begin
   EwbTools.SaveImagesDialog(OleObject, Document);
end;

procedure TEmbeddedWB.OpenOtherWBFavorites;
begin
   EwbTools.OpenOtherWBFavorites(Self);
end;

procedure TEmbeddedWB.ViewPageSourceHtml;
begin
   EwbTools.ViewPageSourceHtml(Document);
end;

procedure TEmbeddedWB.SavePageTextDialog;
begin
   Wait();
   EwbTools.SavePageTextDialog(Self, OleObject, Document);
end;

//Open external programs -------------------------------------------------------

function TEmbeddedWB.OpenAddressBook: Boolean;
begin
   Result := True;
   EwbTools.OpenAddressBook;
end;

function TEmbeddedWB.OpenEudoraMail: Boolean;
begin
   Result := True;
   EwbTools.OpenEudoraMail;
end;

function TEmbeddedWB.OpenOutlookMail: Boolean;
begin
   Result := True;
   EwbTools.OpenOutlookMail;
end;

function TEmbeddedWB.OpenOutlookExpressMail: Boolean;
begin
   Result := True;
   EwbTools.OpenOutlookExpressMail;
end;

function TEmbeddedWB.OpenCalendar: Boolean;
begin
   Result := EwbTools.OpenCalendar()
end;

function TEmbeddedWB.OpenClient(Client: string): Boolean;
begin
   Result := EwbTools.OpenClient(Client);
end;

function TEmbeddedWB.OpenRegistryEditor: Boolean;
begin
   Result := True;
   EwbTools.OpenRegistryEditor;
end;

function TEmbeddedWB.OpenNewsClient: Boolean;
begin
   Result := EwbTools.OpenNewsClient()
end;

function TEmbeddedWB.OpenNetMeeting: Boolean;
begin
   Result := EwbTools.OpenNetMeeting()
end;

procedure TEmbeddedWB.ExploreFolder(Path: string);
begin
   EwbTools.DoExploreFolder(Handle, Path);
end;

procedure TEmbeddedWB.OpenIEBrowserWithAddress;
begin
   EwbTools.OpenIEBrowserWithAddress(Handle);
end;

//Open specific webpages -------------------------------------------------------

function TEmbeddedWB.OpenHotmailMail: Boolean;
begin
   Result := EwbTools.OpenHotmailMail(Self)
end;

function TEmbeddedWB.OpenYahooMail: Boolean;
begin
   Result := EwbTools.OpenGoogleMail(Self)
end;

function TEmbeddedWB.OpenGoogleMail: Boolean;
begin
   Result := EwbTools.OpenGoogleMail(Self)
end;

procedure TEmbeddedWB.GoSearchInGoogle(SearchTerm: string);
begin
   EwbTools.GoSearchInGoogle(Self, SearchTerm)
end;

procedure TEmbeddedWB.GoSearchInMSN(SearchTerm: string);
begin
   EwbTools.GoSearchInMSN(Self, SearchTerm)
end;

procedure TEmbeddedWB.GoSearchInYahoo(SearchTerm: string);
begin
   EwbTools.GoSearchInYahoo(Self, SearchTerm)
end;

//Navigate & Download ----------------------------------------------------------

procedure TEmbeddedWB.GoDownloadFile(URL: string);
begin
   EwbTools.GoDownloadFile(Self, URL);
end;

procedure TEmbeddedWB.GoDownloadMaskedFile(SourceFile, TargetFile: string; Notify: Boolean);
begin
   EwbTools.GoDownloadMaskedFile(SourceFile, TargetFile, Notify);
end;

procedure TEmbeddedWB.GoWithQueryDetails(Url, Query: string);
begin
   EwbTools.GoWithQueryDetails(Self, Url, Query);
end;

procedure TEmbeddedWB.GoNoHistory(const URL: string);
begin
   EwbTools.GoNoHistory(Self, URL);
end;

procedure TEmbeddedWB.NavigateFolder(CSIDL: Integer);
begin
   EwbTools.NavigateFolder(Self, CSIDL);
end;

function TEmbeddedWB.NavigateToFrame(FrameList: string): IHtmlDocument2;
begin
   Result := EwbTools.NavigateToFrame(Self, FrameList);
end;

procedure TEmbeddedWB.GoAboutBlank;
begin
   EwbTools.GoAboutBlank(Self);
end;

function TEmbeddedWB.DownloadFile(SourceFile, DestFile: string): Boolean;
begin
   Result := EwbTools.DownloadFile(SourceFile, DestFile);
end;

//Get Special Folders/URL paths etc.--------------------------------------------

function TEmbeddedWB.GetCookiesPath: string;
begin
   Result := EwbTools.GetCookiesPath;
end;

function TEmbeddedWB.GetHistoryPath: string;
begin
   Result := EwbTools.GetHistoryPath;
end;

function TEmbeddedWB.GetFavoritesPath: string;
begin
   Result := EwbTools.GetFavoritesPath;
end;

function TEmbeddedWB.GetDefaultBrowserFromRegistry: string;
begin
   Result := EwbTools.GetDefaultBrowserFromRegistry;
end;

function TEmbeddedWB.GetSpecialFolderPath(CallerHandle: THandle; CSIDL: Integer): PChar;
begin
   Result := EwbTools.GetSpecialFolderPath(CallerHandle, CSIDL);
end;

function TEmbeddedWB.GetCachedFileFromURL(strUL: string; var strLocalFile: string): Boolean;
begin
   Result := EwbTools.GetCachedFileFromURL(strUL, strLocalFile)
end;

function TEmbeddedWB.URLFromFavorites(const dotURL: string): string;
begin
   Result := EwbTools.URLFromFavorites(dotURL);
end;

function TEmbeddedWB.UrlFromHistory(ShellFolder: IShellFolder; pidl: PItemIDList): string;
begin
   Result := EwbTools.UrlFromHistory(ShellFolder, pidl)
end;

function TEmbeddedWB.GetIPAndHostName(var HostName, IPaddr, WSAErr: string): Boolean;
begin
   Result := EwbTools.GetIPAndHostName(HostName, IPaddr, WSAErr);
end;

//E-Mail functions--------------------------------------------------------------

procedure TEmbeddedWB.SendPageInMailAsAttachment(aOwner: TComponent; FileName, Subject, Body: string);
begin
   EwbTools.SendPageInMailAsAttachment(Self, aOwner, Document, FileName, Subject, Body);
end;

procedure TEmbeddedWB.CreateNewMail;
begin
   EwbTools.CreateNewMail;
end;

procedure TEmbeddedWB.SendUrlInMail;
begin
   EwbTools.SendUrlInMail(LocationURL, LocationName);
end;

//Search in Document & Fill Forms-----------------------------------------------

function TEmbeddedWB.SearchText(const Value: string; const iPos: Integer = 1): IHTMLTxtRange;
begin //by JJM
   Result := EwbTools.SearchText(Self, Document, Value, iPos);
end;

function TEmbeddedWB.SearchString(const strText: string): Boolean;
begin
   Result := EwbTools.SearchString(Self, strText);
end;

procedure TEmbeddedWB.SearchAndHighlight(const ACaption, APrompt: string; aText: string = ''; ShowInputQuery: Boolean = False);
begin
   Wait();
   EwbTools.SearchAndHighlight(Document, ACaption, APrompt, aText, ShowInputQuery);
end;

function TEmbeddedWB.FillForm(FieldName: string; Value: string): Boolean;
begin
   Result := EwbTools.FillForm(OleObject, FieldName, Value)
end;

procedure TEmbeddedWB.AutoFillIEFormAndExcecute;
begin
   EwbTools.AutoFillIEFormAndExcecute
end;

//Clearing Cache/History/Typed Urls---------------------------------------------

procedure TEmbeddedWB.ClearCache;
begin
   EwbTools.ClearCache;
end;

procedure TEmbeddedWB.ClearTypedUrls;
begin
   EwbTools.ClearTypedUrls;
end;

procedure TEmbeddedWB.ClearHistory;
begin
   EwbTools.ClearHistory;
end;

//Online Status-----------------------------------------------------------------

function TEmbeddedWB.CheckOnlineStatus: Boolean;
begin
   Result := EwbTools.CheckOnlineStatus;
end;

function TEmbeddedWB.IsGlobalOffline: Boolean;
begin
   Result := EwbTools.IsGlobalOffline;
end;

procedure TEmbeddedWB.WorkOnline;
begin
   EwbTools.WorkOnline(Self);
end;

procedure TEmbeddedWB.WorkOffline;
begin
   EwbTools.WorkOffline(Self);
end;

//Restricted & Trusted Lists----------------------------------------------------

procedure TEmbeddedWB.AddToRestrictedSiteList(URL: string);
begin
   EwbTools.AddToRestrictedSiteList(Self, URL);
end;

procedure TEmbeddedWB.AddToTrustedSiteList(URL: string);
begin
   EwbTools.AddToTrustedSiteList(Self, URL);
end;

function TEmbeddedWB.CheckIfInTrustedList(const Host: string; SecureSite: boolean): Boolean;
begin
   Result := EwbTools.CheckIfInTrustedList(Host, SecureSite);
end;

function TEmbeddedWB.CheckIfInRestricredList(Host: string; SecureSite: boolean): Boolean;
begin
   Result := EwbTools.CheckIfInRestricredList(Host, SecureSite);
end;

//Zone Icon, Security Zone, SSL Status  ----------------------------------------

procedure TEmbeddedWB.GetZoneIcon(IconPath: string; var Icon: TIcon);
begin
   EwbTools.GetZoneIcon(IconPath, Icon);
end;

function TEmbeddedWB.GetZoneAttributes(const URL: string): TZoneAttributes;
begin
   Result := EwbTools.GetZoneAttributes(LocationURL);
end;

function TEmbeddedWB.GetZoneIconToForm: Boolean;
begin
   Result := EwbTools.GetZoneIconToForm(LocationURL, Caption, Hint);
end;

function TEmbeddedWB.GetSSLStatus(var SSLName, SSLDescription: string): Boolean;
begin
   Result := EwbTools.GetSSLStatus(OleObject, LocationURL, SSLName, SSLDescription);
end;

function TEmbeddedWB.GetUrlSecurityZone(var ZoneName, ZoneDescription: string; var Icon: TIcon): Boolean;
begin
   Result := EwbTools.GetUrlSecurityZone(LocationURL, ZoneName, ZoneDescription, Icon);
end;

//Proxy & User agent -----------------------------------------------------------

procedure TProxySettings.SetProxy(UserAgent, Address: string);
begin
   bProxy := True;
   EwbTools.SetProxy(UserAgent, Address);
end;

procedure TProxySettings.SetProxy(UserAgent, Address, UserName, Password: string; Port: integer);
begin
   bProxy := True;
   EwbTools.SetProxy(UserAgent, Address, UserName, Password, Port);
end;

procedure TEmbeddedWB.SetUserAgent;
begin
   EwbTools.SetUserAgent(FUserAgent);
end;

//Miscellaneous  ---------------------------------------------------------------

procedure TEmbeddedWB.RestoreApplicationFormSize;
begin
   EwbTools.RestoreApplicationFormSize(Self);
end;

procedure TEmbeddedWB.SaveApplicationFormSize;
begin
   EwbTools.SaveApplicationFormSize(Self);
end;

procedure TEmbeddedWB.ShowIEVersionInfo;
begin
   EwbTools.ShowIEVersionInfo(Handle);
end;

procedure TEmbeddedWB.SetNewHomePage(HomePage: string);
begin
   EwbTools.SetNewHomePage(HomePage);
end;

function TEmbeddedWB.GetLastVisitedPage(var LastVisitedPage: string): Boolean;
begin
   Result := EwbTools.GetLastVisitedPage(LastVisitedPage);
end;

function TEmbeddedWB.SaveLastVisitedPage: Boolean;
begin
   Result := EwbTools.SaveLastVisitedPage(Self, LocationURL);
end;

procedure TEmbeddedWB.AddToFavorites(URL, Title: string);
begin
   inherited;
   EwbTools.AddToFavorites(URL, Title);
end;

procedure TEmbeddedWB.CreateDesktopShortcut;
begin
   EwbTools.CreateDesktopShortcut(Handle);
end;

procedure TEmbeddedWB.DisableNavSound(bDisable: Boolean);
begin
   EwbTools.DisableNavSound(bDisable);
end;

function TEmbeddedWB.IsValidProtocol(const URL: string): Boolean;
begin
   Result := EwbTools.IsValidProtocol(URL);
end;

function TEmbeddedWB.DecodeUrl(const InputStr: string): string;
begin
   Result := EwbTools.DecodeUrl(InputStr);
end;

function TEmbeddedWB.EncodeUrl(const InputStr: string; const bQueryStr: Boolean): string;
begin
   Result := EwbTools.EncodeUrl(InputStr, bQueryStr);
end;
{$ENDIF}
//End of EwbTools---------------------------------------------------------------

procedure DoFinalization;
begin
{$IFDEF USE_EwbDDE}{$IFDEF DELPHI_6_UP}
{$WARN SYMBOL_DEPRECATED OFF}
   DeAllocateHWND(DDEHWND);
{$WARN SYMBOL_DEPRECATED ON}
{$ENDIF}{$ENDIF}
   if bProxy then
      RemoveProxy;
   {$IFDEF USE_EwbTools}
   if bNavSound then
      DisableNavSound(False);
   {$ENDIF}
   RemoveUserAgent;
   Set8087CW(wSaved8087CW);
   if bOleInitialize then    
   try
      OleUninitialize;
   except
   end;
end;

procedure DoInitialization;
begin
   wSaved8087CW := Default8087CW;
   bPrintOptionsEnable := False;
   bProxy := False;
   bHook := False;
   bNavSound:= False;
   bMessageH:= False;
   if OleInitialize(nil)= S_OK then
      bOleInitialize := True;
end;

initialization
   DoInitialization;
finalization
   DoFinalization;
end.




